<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use \app\admin\model\exchange\Code as LibraryCode;
use \app\admin\model\exchange\Library;
use \app\common\model\FttuserToken;
use \app\admin\model\exchange\Log;
use \think\Log as Logs;

/**
 * 示例接口
 */
class Code extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['update_soft','update_dow'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new LibraryCode;
//        $token = $this->request->header('token');
//        if (empty($token)) {
//            $this->error("token不能为空");
//        }
//        $user_token = (new FttuserToken())->where(['token' => $token])->find();
//        if (empty($user_token)) {
//            $this->error("请先登录");
//        } else {
//            $this->user_id = $user_token['user_id'];
//        }
    }

    /**
     * 提货劵接口：罗列当前我的提货劵  三个状态 未使用 已使用  已过期
     */
    public function lists()
    {
        $where = array('user_id' => $this->user_id);
        $status = $this->request->post("status"); // 状态
        if (!$status) {
            $this->error("状态不能为空");
        }

        $offset = $this->request->post("offset"); // 第几页
        $offset = empty($offset) ? 0 : bcsub($offset, 1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $limit = empty($limit) ? 10 : $limit;
        $page = bcmul($offset, $limit);
        $pag_limit = bcadd($offset, 1) * $limit;
        $list = $this->model
            ->alias('code')
            ->with(['library'])
            ->where($where)
            ->where('code.status', $status)
            ->order('code.end_time', 'desc')
            ->limit($page, $pag_limit)->select();

        $this->success('成功', $list);
    }


    /**
     * 转增接口：录入平台存在的手机号，可以转增，否则转增不了
     */
    public function increase()
    {
        $mobile = $this->request->post("mobile"); // 手机号
        $id = $this->request->post("id"); // ID
        $fttuser = Db::connect('database_b')->table('fttuser')->where(['cellphone' => $mobile])->find();
        if (empty($fttuser)) {
            $this->error('手机号不存在');
        }
        $row = $this->model->get($id);
        if (empty($row)) {
            $this->error("提货券不存在");
        }
        if ($row['status'] == 2) {
            $this->error("提货券已使用");
        }
        if ($row['status'] == 3) {
            $this->error("提货券已过期");
        }
        $data = array(
            'user_id' => $fttuser['user_id'],
            'mobile' => $mobile,
        );
        $result = $this->model->where(['id' => $id])->update($data);

        // 记录
        $log = array(
            'subgift_user_id' => $this->user_id,
            'user_id' => $fttuser['user_id'],
            'code_id' => $row['id'],
            'code' => $row['code']
        );
        (new Log())->save($log);
        if ($result) {
            $this->success('成功', $result);
        } else {
            $this->error("失败");
        }
    }

    /**
     * 核销接口，验证提货劵是否有效
     */
    public function writeoff()
    {
        $code_id = $this->request->post("code_id"); // ID
        $row = $this->model->get($code_id);
        if (empty($row)) {
            $this->error("提货券不存在");
        }
        if ($row['status'] == 2) {
            $this->error("提货券已使用");
        }
        if ($row['status'] == 3) {
            $this->error("提货券已过期");
        }

        $Library = (new Library())->get($row['library_id']);
        $item_id = $this->request->post("item_id"); // 商品ID
        $real_name = $this->request->post("real_name"); // 收货人姓名
        $user_phone = $this->request->post("user_phone"); // 收货人手机号
        $province = $this->request->post("province"); // 省
        $city = $this->request->post("city"); // 市
        $district = $this->request->post("district"); // 区
        $address_detail = $this->request->post("address_detail"); // 详细地址
        $goods_detail = $this->request->post("goods_detail"); // 商品详情
        $pic_url = $this->request->post("pic_url"); // 商品图片
        $pic_url_json = $this->request->post("pic_url_json"); // 轮播图
        $body = $this->request->post("body"); // 商品内容
        $goods_type = $this->request->post("goods_type"); // 商品类型
        $total_price = $this->request->post("total_price"); // 订单总价
        $app_id = $this->request->post("app_id");
        if (empty($app_id)) {
            $app_id = "coupons";
        }

        // 添加订单
        $data = array(
            'created_at' => date("Y-m-d H:i:s"),
            'uid' => $this->user_id,
            'item_id' => $item_id,
            'out_trade_no' => $this->english_num(),
            'real_name' => $real_name,
            'user_phone' => $user_phone,
            'province' => $province,
            'city' => $city,
            'district' => $district,
            'address_detail' => $address_detail,
            'goods_detail' => $goods_detail,
            'pic_url' => $pic_url,
            'pic_url_json' => $pic_url_json,
            'body' => $body,
            'goods_type' => $goods_type,
            'total_price' => $total_price,
            'handling_method' => 1, // 办理方式 0-分期 1-不分期 2-赠送
            'pay_time' => date("Y-m-d H:i:s"), //支付方式
            'pay_type' => 'coupons_app',//支付方式
            'pay_price' => $Library['money'],
            'pay_status' => 1, //支付状态
            'status' => 1,//订单状态
            'app_id' => $app_id,
            'card_sn' => '-',
            'deduction_amount' => '0.00'
        );
        $order_id = Db::connect('database_b')->table('orders')->insertGetId($data);
        $result = $this->model->where(['id' => $code_id])->update(['status' => 2, 'order_id' => $order_id]);

        if ($result) {
            $this->success('成功', $result);
        } else {
            $this->error("失败");
        }
        $this->success('返回成功', ['action' => 'test1']);
    }

    private function english_num()
    {
        $s = '0123456789qwertyuioplkjhgfdsazxcvbnm';
        $temp = '';
        while (strlen($temp) < 32) {
            $index = mt_rand(0, strlen($s) - 1);
            $temp .= $s[$index];
        }
        return $temp;
    }

    /**
     * @return void
     * 是否需要升级
     */
    public function update_soft()
    {
        $cur_version = Db::name('config')->where("name", 'update_soft')->value('value');
        $update_soft_msg = Db::name('config')->where("name", 'update_soft_msg')->value('value');
        $update_soft_url = Db::name('config')->where("name", 'update_url')->value('value');
        $version = input("version");

        $update_soft_url = str_replace("%NUM%", $cur_version,$update_soft_url);
//        Logs::error($cur_version . ',' . $version);
        if ($version < intval($cur_version)) {

            return $this->success('返回成功', [
                'action' => 1,
                'url' => $update_soft_url,
                'msg' => $update_soft_msg,
            ]);
        }

        $this->success('返回成功', ['action' => 0]);
    }
    /**
     * @return void
     * 扫描下载
     */
    public function update_dow()
    {
        $cur_version = Db::name('config')->where("name", 'update_soft')->value('value');
        $update_soft_msg = Db::name('config')->where("name", 'update_soft_msg')->value('value');
        $update_soft_url = Db::name('config')->where("name", 'update_url')->value('value');

        $update_soft_url = str_replace("%NUM%", $cur_version,$update_soft_url);
        return $this->success('返回成功', [
            'action' => 1,
            'url' => $update_soft_url,
            'msg' => $update_soft_msg,
        ]);
    }
}
